package com.zibo.convalesce.modules.login.controller;

import com.zibo.convalesce.common.result.AjaxMapResult;
import com.zibo.convalesce.modules.login.pojo.AdminLoginResp;
import com.zibo.convalesce.modules.login.service.AdminLoginService;
import com.zibo.convalesce.modules.login.pojo.AdminLoginReq;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 管理员登录
 *
 * @author lx
 */
@Api(description = "管理员登录相关接口")
@RestController
@RequestMapping("/admin")
public class AdminLoginController {

    private static final Logger logger = LoggerFactory.getLogger(AdminLoginController.class);

    @Autowired
    private AdminLoginService adminLoginService;

    private boolean login;

    /**
     * 管理员登录接口
     *
     * @param request
     * @param session
     * @param loginReq
     * @return
     */
    @ApiOperation(value = "管理员登录")
    @RequestMapping(value = "/loginIn")
    public AjaxMapResult loginIn(HttpServletRequest request, HttpSession session,AdminLoginReq loginReq) {

        logger.info("进入首页登录接口，接口入参:{}", loginReq);
        if (null == loginReq) {
            return AjaxMapResult.error("请求参数不能为空");
        }

        // 判断session中的验证码跟输入的是否一致
        if (loginReq.getCaptcha().equalsIgnoreCase(String.valueOf(request.getSession().getAttribute("captCode")))) {

            // 查询是否存在该用户
            AdminLoginResp adminLoginResp = adminLoginService.queryCourtyard(loginReq);
            logger.info("登录用户信息===>{}" ,adminLoginResp);

            String courtyardReq = loginReq.getCourtyard();
            String courtyardResp = adminLoginResp.getCourtyard();
            if (adminLoginResp == null || !courtyardReq.equals(courtyardResp)) {
                return AjaxMapResult.error("登录用户不存在");
            }

            login = adminLoginService.login(loginReq);
            if (login) {
                // 把登录信息设置到session中
                session.setAttribute("username", loginReq.getUsername());
                session.setAttribute("courtyard", loginReq.getCourtyard());
                session.setAttribute("admin", adminLoginResp);
                return AjaxMapResult.success(Integer.parseInt(adminLoginResp.getPower()), "登录成功");
            } else {
                return AjaxMapResult.error("登录名或密码错误");
            }
        }
        return AjaxMapResult.error("验证码错误");
    }
}